﻿
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Xml.Serialization;
using RemoteTestRunner.Contracts;

namespace RemoteTestRunner.DataAccess
{
    public class TestProjectAccess
    {
        #region Private Attributes

        private readonly string _dataPath;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="TestProjectAccess"/> class.
        /// </summary>
        /// <param name="path">The path.</param>
        public TestProjectAccess(string path)
        {
            _dataPath = path;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Gets the list of configured test projects and related information.
        /// </summary>
        /// <returns>A list of <see cref="Project"/>.</returns>
        public List<Project> GetProjects()
        {
            if (!File.Exists(_dataPath))
            {
                var emptyProjects = new List<Project>();

                SaveProjects(emptyProjects);
            }

            using (var fileStream = File.OpenRead(_dataPath))
            {
                var serializer = new XmlSerializer(typeof(List<Project>));
                var projects = serializer.Deserialize(fileStream) as List<Project>;

                return projects;
            }
        }

        /// <summary>
        /// Saves the list of projects.
        /// </summary>
        /// <param name="projects">The projects to be saved.</param>
        public void SaveProjects(IList<Project> projects)
        {
            // Open in "Create" mode because the serializer does not "resize" files based on content
            using (var fileStream = File.Open(_dataPath, FileMode.Create))
            {
                var serializer = new XmlSerializer(typeof(List<Project>));

                serializer.Serialize(fileStream, projects);
            }
        }

        /// <summary>
        /// Gets a <see cref = "DataRow" /> containing information for the specified test ID.
        /// </summary>
        /// <param name = "testId">The test ID to retrieve information for.</param>
        /// <returns>A <see cref = "DataRow" /> containing information for the specified test.</returns>
        public DataRow GetTestRow(int testId)
        {
            // TODO: REMOVE THIS METHOD / REPLACE IT WITH A NEW ONE (USING THE XML FILE)
            //var rows = _dataSet.Test.Select("ID = " + testId);

            //if (rows.Length == 0)
            //{
            //    return null;
            //}

            //return rows[0];

            return null;
        }


        #endregion
    }
}